package com.duan.laugh.sms.core;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import javax.sql.DataSource;
import java.util.List;

/**
 * 短信自动配置
 *
 * @author duanjw
 */
@Configuration
@EnableConfigurationProperties({SmsAccessProperties.class})
public class SmsAutoConfiguration {
    /**
     * redis中的短信账户
     *
     * @return
     */
    @Bean
    public RedisSmsAccountRepository redisEmailAccountDefinitionRepository(RedisConnectionFactory redisConnectionFactory) {
        return new RedisSmsAccountRepository(redisConnectionFactory);
    }

    /**
     * 内存中的短信账户
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(SmsAccountRepository.class)
    public InMemoryEmailAccountRepository inMemoryMailAccountStore() {
        return new InMemoryEmailAccountRepository();
    }

    /**
     * jdbc的短信账户初始化到存储器里
     *
     * @param dataSource
     * @param smsAccountRepository
     * @return
     */
    @Bean
    public InitJdbcSmsAccount2Repository initJdbcEmailAccount2Repository(DataSource dataSource, SmsAccountRepository smsAccountRepository) {
        return new InitJdbcSmsAccount2Repository(dataSource, smsAccountRepository);
    }

    /**
     * 配置文件中的短信账户
     *
     * @param smsAccessProperties
     * @return
     */
    @Bean
    public PropertiesSmsAccountLocator propertiesEmailAccountLocator(SmsAccessProperties smsAccessProperties) {
        return new PropertiesSmsAccountLocator(smsAccessProperties);
    }


    /**
     * 短信账户定位器，包括所有的短信定位器
     *
     * @param smsAccountLocators
     * @return
     */
    @Bean
    @Primary
    public SmsAccountLocator emailAccountLocator(
            List<SmsAccountLocator> smsAccountLocators) {
        return new CompositeSmsAccountLocator(smsAccountLocators);
    }

    /**
     * 短信渠道
     * @param smsChannels
     * @return
     */
    @Bean
    public SmsChannelFactory smsChannelStrategy(List<SmsChannel> smsChannels) {
        return new SmsChannelFactory(smsChannels);
    }
}
